﻿using DevExpress.ExpressApp.Blazor.Components.Models;

namespace EasyXaf.DynamicForm.Blazor.Components;

public class NumberComponent<T> : FieldComponent
{
    protected override object ConvertValue(object value)
    {
        if (typeof(T) == typeof(int))
        {
            if (int.TryParse(value?.ToString(), out var number))
            {
                return number;
            }
        }
        else if (typeof(T) == typeof(double))
        {
            if (double.TryParse(value?.ToString(), out var number))
            {
                return number;
            }
        }

        if (Field.Required == true)
        {
            return default(T);
        }

        return null;
    }

    protected override ComponentModelBase CreateComponentModel()
    {
        var model = new DxSpinEditModel<T>
        {
            Id = Field.Id
        };

        if (Field.Attributes.TryGetValue("min-value", out var minValue))
        {
            if (typeof(T) == typeof(int) && int.TryParse(minValue, out var intValue))
            {
                model.MinValue = (T)(object)intValue;
            }
            else if (typeof(T) == typeof(double) && double.TryParse(minValue, out var doubleValue))
            {
                model.MinValue = (T)(object)doubleValue;
            }
        }

        if (Field.Attributes.TryGetValue("max-value", out var maxValue))
        {
            if (typeof(T) == typeof(int) && int.TryParse(maxValue, out var intValue))
            {
                model.MaxValue = (T)(object)intValue;
            }
            else if (typeof(T) == typeof(double) && double.TryParse(maxValue, out var doubleValue))
            {
                model.MaxValue = (T)(object)doubleValue;
            }
        }

        if (Field.Attributes.TryGetValue("step", out var step))
        {
            if (typeof(T) == typeof(int) && int.TryParse(step, out var intValue))
            {
                model.Increment = (T)(object)intValue;
            }
            else if (typeof(T) == typeof(double) && double.TryParse(step, out var doubleValue))
            {
                model.Increment = (T)(object)doubleValue;
            }
        }

        if (Field.Attributes.TryGetValue("format", out var format))
        {
            model.DisplayFormat = format;
        }

        return model;
    }
}
